﻿using CommunityToolkit.Maui.Core;
using Compass.Maui.Pages.FinishGoods;
using Compass.Maui.Services.FinishGoods;

namespace Compass.Maui.ViewModels.FinishGoods;
[QueryProperty(nameof(PackingListDto), nameof(PackingListDto))]
public partial class WeighingPageViewModel : BaseViewModel
{
    private readonly IPalletService _palletService;
    private readonly INavigationService _navigationService;

    public WeighingPageViewModel(IPalletService palletService, IPopupService popupService, INavigationService navigationService)
    {
        _palletService = palletService;
        _navigationService = navigationService;
        palletService.Update += PalletServiceOnUpdate;
    }
    [ObservableProperty]
    private PackingListDto packingListDto;
    public ObservableRangeCollection<PalletDto> PalletDtos { get; } = new();


    [RelayCommand]
    private async Task GetPalletDtosAsync()
    {
        await IsBusyFor(async () =>
        {
            try
            {
                PalletDtos.ReplaceRange(await _palletService.GetPalletsByPackingListIdAsync(PackingListDto.Id.Value));
            }
            catch (Exception e)
            {
                await Shell.Current.DisplayAlert("Error!", $"Unable to get pallets:{e.Message}", "OK");
            }
        });
    }

    [RelayCommand]
    private async Task GoToWeighingPalletAsync(PalletDto? palletDto)
    {
        await IsBusyFor(async () =>
        {
            if (palletDto is null) return;
            await _navigationService.NavigateToAsync(nameof(WeighingPalletPage),
                new Dictionary<string, object>()
                {
                    {nameof(PalletDto),palletDto}
                });
        });
    }

    [RelayCommand]
    private async Task AddPallet()
    {
        PackingListDto.HavePallet = true;
        await GoToWeighingPalletAsync(new PalletDto()
        {
            PalletNumber = PalletDtos.Max(x => x.PalletNumber) is null ? 1 : PalletDtos.Max(x => x.PalletNumber)+1,
            MainPlanId = PackingListDto.Id,
        });
    }

    //响应Pallet更新事件，更新入库时间
    private void PalletServiceOnUpdate(object? sender, PalletUpdateEventArgs e)
    {
        PalletDtos.Replace(e.UpdatedPalletDto);
    }
}